﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RTMP
{
    public class Fourcc
    {
        static string _guid = "0000-0010-8000-00AA00389B71";

        uint _code;

        public Fourcc(string s)
        {
            if (s == null || s.Length != 4)
            {
                throw new ArgumentException();
            }

            _code = 0;

            foreach (char c in s)
            {
                if (c > 0xff)
                {
                    throw new ArgumentException();
                }

                _code = (_code << 8) | (uint)c;
            }
        }

        public Fourcc(uint code)
        {
            _code = code;
        }

        public Fourcc(Guid guid)
        {
            if (String.Compare(guid.ToString("D").Substring(9), _guid, true) != 0)
            {
                throw new ArgumentException();
            }

            _code = 0;

            byte[] bytes = guid.ToByteArray();

            for (int i = 0; i < 4; i++)
            {
                _code = (_code << 8) | (uint)bytes[i];
            }
        }

        public override string ToString()
        {
            string s = "";

            for (int i = 3; i >= 0; i--)
            {
                s += (char)((_code >> (i * 8)) & 0xff);
            }

            return s;
        }

        public uint ToUInt32()
        {
            return _code;
        }

        public Guid ToGuid()
        {
            string s = String.Format("{0:X8}-{1}", _code, _guid);

            return new Guid(s);
        }

        public static implicit operator string(Fourcc f)
        {
            return f.ToString();
        }

        public static implicit operator uint(Fourcc f)
        {
            return f.ToUInt32();
        }

        public static implicit operator Guid(Fourcc f)
        {
            return f.ToGuid();
        }
    }
}
